package com.mars.security.core.social.qq.connect;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import org.slf4j.Logger;

/**
 * 自定义OAuth2模板里的个别方法，实现将响应数据转换为json的方法
 * @Author: Mars
 * @Date: 2018/9/14 15:46
 */
public class QQOAuth2Template extends OAuth2Template{

    private Logger logger = LoggerFactory.getLogger(getClass());

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        /**
         * accessTokenUrl:授权的url
         * parameters：请求的参数
         * String.class：返回数据的响应类型
         */
        String responseStr = getRestTemplate().postForObject(accessTokenUrl,parameters,String.class);
        logger.info("获取accessToken的响应：" + responseStr);

         // 切割获取的响应字符串
        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr,"&");
        String accessToken = StringUtils.substringAfterLast(items[0],"=");
        Long expiresIn = new Long(StringUtils.substringAfterLast(items[1],"="));
        String refreshToken = StringUtils.substringAfterLast(items[2],"=");

        return super.postForAccessGrant(accessTokenUrl, parameters);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        // 先获取父类的AuthTemplate返回结果
        RestTemplate restTemplate = super.createRestTemplate();
        // 获取信息转换器，添加新的转换器，可以将 text/html 格式的数据进行转换
        restTemplate.getMessageConverters().add(
                new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}
